package com.emp.view.controller;

import com.emp.view.service.EmpSerivce;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.song.emp.vo.EmpVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
public class EmpController {

    @Resource
    private EmpSerivce empSerivce;
    @Resource
    private RestTemplate restTemplate;

    private static  final String EMP_PROVIDER="http://localhost:9001/";
    @GetMapping("/list")
    @HystrixCommand(fallbackMethod = "hystrix")
    public List<EmpVo> findAll(){
        return this.restTemplate.getForObject(EMP_PROVIDER+"emps", List.class);
        //return this.empSerivce.findEmps();
    }

    /**
     * 熔断的方法
     * 注意熔断的方法的返回值必须与原方法类型相同！！！
     * @return
     */
    public List<EmpVo> hystrix(){
        List<EmpVo> list=new ArrayList<EmpVo>();
        EmpVo vo=new EmpVo();
        vo.setName("熔断了！！！！1");
        list.add(vo);
        return list;
    }

    @GetMapping("/depts")
    public List<EmpVo> findDepts() {
        return this.restTemplate.getForObject(EMP_PROVIDER+"depts", List.class);
//        return this.empSerivce.findDepts();
    }

    @PostMapping("/save")
    public boolean save(EmpVo empVo){
        this.restTemplate.postForObject(EMP_PROVIDER + "save", empVo, EmpVo.class);
        return true;
        //return this.empSerivce.save(empVo);
    }

    @GetMapping("/del/{eid}")
    public boolean del(@PathVariable("eid")int eid){
        Integer forObject = this.restTemplate.getForObject(EMP_PROVIDER + "del/"+eid, Integer.class);
//        System.err.println(forObject);
//        return forObject!=null ? true:false;
        return true;
        // return this.empSerivce.delete(eid);
    }

    @GetMapping("/find/{eid}")
    public EmpVo find(@PathVariable("eid")int eid){
        //this.restTemplate.getForObject(EMP_PROVIDER + "find/{eid}", int.class, eid);
        return this.empSerivce.findById(eid);
    }
}
